﻿using NCP.Core.DataUtil;
using NCP.Model;
using NCP.Util.CusAttributes;
using SqlSugar.Extensions;
using System;
using System.Collections.Generic;
using System.Reflection;

namespace NCP.Core
{
    public static class CommonUtil
    {
        public static void BuildText<T>(T model)
        {
            Type t = typeof(T);
            foreach (var p in t.GetProperties())
            {
                ExplainAttribute explain = p.GetCustomAttribute<ExplainAttribute>();
                if (explain != null)
                {
                    object obj = t.GetProperty(explain.SourceField).GetValue(model);
                    if (obj == null)
                        continue;
                    string val = string.Empty;
                    if (explain.CacheKey == KeyEnum.Dept)
                    {
                        val = GetDept(obj.ToString());
                    }
                    if (explain.CacheKey == KeyEnum.Member)
                    {
                        val = GetMemberName(obj.ObjToString());
                    }
               
                    p.SetValue(model, val);
                }
            }
        }

        public static string GetDept(string deptCode)
        {
            List<DeptInfo> deptList = DbHelper.GetSqlSugarClient().Queryable<DeptInfo>().WithCache(3600).ToList();//缓存1个小时
            DeptInfo dept = deptList.Find(b => b.DeptCode == deptCode);
            if (dept != null)
                return dept.DeptName;
            return string.Empty;
        }

        public static string GetMemberName(string code)
        {
            List<Member> memberList = DbHelper.GetSqlSugarClient().Queryable<Member>().WithCache(3600).ToList();//缓存1个小时
            Member member = memberList.Find(b => b.Code == code);
            if (member != null)
                return member.Name;
            return string.Empty;
        }


    }
}
